import {Component, OnInit, OnChanges} from '@angular/core';
import {PaginationModel} from "./pagination.model";
import {Input} from "@angular/core/src/metadata/directives";

/**
 * paginationConfig: PaginationModel
 *
 */
@Component({
  selector: 'iotek-pagenation',
  templateUrl: './pagenation.component.html',
  styleUrls: ['./pagenation.component.less']
})
export class PagenationComponent implements OnInit, OnChanges {

  constructor() { }

  public ngOnInit() {
  }

  private paginationSize = {
    "sm" : 2,
    "md" : 4,
    "lg" : 6
  };
  public pageNoList:{}[] = [];
  public ngOnChanges(): void {
    this.pageNoList = this.generatePaginationArray(this.config.totalPage, this.config.currentPage, this.config.size);
  }

  @Input("paginationConfig")
  public config: PaginationModel;


  private generatePaginationArray(totalPage: number, currentPage: number, size: string): {}[] {
    let front: {}[] = [];
    let last: {}[] = [];
    let pager: {}[];
    if(currentPage - 1 <= this.paginationSize[size]) {
      // 前面顺子
      front = this.getContinuousNumbers(1, currentPage - 1);
    } else {
      // 前面有省略
      front.push({
        text: '1',
        pn: 1
      });
      front.push({
        text: '...',
        pn: currentPage - (this.paginationSize[size] - 1)
      });
      for(var i = currentPage - (this.paginationSize[size] - 2); i <= currentPage - 1; i++) {
        front.push({
          text: i + "",
          pn: i
        });
      }
    }
    if(totalPage - currentPage <= this.paginationSize[size]) {
      // 后面顺子
      last = this.getContinuousNumbers(currentPage + 1, totalPage);
    } else {
      // 后面有省略
      for(var j = currentPage + 1; j < (currentPage + this.paginationSize[size] - 1); j++) {
        last.push({
          text: j + "",
          pn: j
        });
      }
      last.push({
        text: "...",
        pn: (currentPage + this.paginationSize[size] - 1)
      });
      last.push({
        text: totalPage + "",
        pn: totalPage
      });
    }
    pager = front.concat({
        text: (currentPage) + "",
        pn: (currentPage)
      }).concat(last);
    return pager;
  }

  private getContinuousNumbers(start: number, end: number): {}[] {
    let numbers: {}[] = [];
    for(var i = start; i <= end; i++) {
      numbers.push({
        text: i + "",
        pn: i
      });
    }
    return numbers;
  }

}
